package ActingMode.Dynamicagent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//用这个类来自动生成一个代理类
public class ProxyInvocationHandler implements InvocationHandler {

    //被代理的接口
    private Object target;

    //设置要代理的对象
    public void setTarget(Object target){
        this.target = target;
    }

    //生成得到代理类
    public Object getProxy()  {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
    }

    //处理代理实例并返回结果
    public Object invoke(Object proxy,Method method,Object[] args){
        log(method.getName());
        Object result = null;
        try {
            result = method.invoke(target, args);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void log(String msg){
        System.out.println("执行了"+msg+"方法");
    }
}
